package org.jeecg.modules.common.task;
import org.jeecg.modules.common.bean.mqtt.MqttCamelliaStatusBean.CamelliaSubDeviceStatus;
import org.jeecg.modules.common.bean.mqtt.MqttCamelliaStatusBean.CamelliaDeviceTem;
import org.jeecg.modules.common.bean.mqtt.MqttCamelliaStatusBean.CamelliaDevicePressure;
import org.jeecg.modules.common.bean.mqtt.MqttCamelliaStatusBean.CamelliaSolenoidStatus;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.common.bean.MqttClientInfo;
import org.jeecg.modules.common.bean.mqtt.MqttCamelliaStatusBean;
import org.jeecg.modules.common.bean.mqtt.MqttThresholdBean;
import org.jeecg.modules.common.entity.CamelliaDevice;
import org.jeecg.modules.common.service.ICamelliaDeviceService;
import org.jeecg.modules.common.service.ICamelliaDeviceTypeService;
import org.jeecg.modules.common.service.MqttHttpApi;
import org.jeecg.modules.common.service.MqttService;
import org.jeecg.modules.env.controller.CamelliaEnvSysController;
import org.jeecg.modules.env.entity.CamelliaEnvSys;
import org.jeecg.modules.env.entity.CamelliaEnvThreshold;
import org.jeecg.modules.env.service.ICamelliaEnvSysService;
import org.jeecg.modules.env.service.ICamelliaEnvThresholdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @Classname TimeTask
 * @Description TODO
 * @Date 2022/12/3 20:03
 * @Created by 10835
 */
@Slf4j
@Component
public class TimeTask {
    @Resource
    private MqttHttpApi httpApi;
    @Autowired
    private ICamelliaDeviceService camelliaDeviceService;

    @Autowired
    private ICamelliaDeviceTypeService camelliaDeviceTypeService;

    @Autowired
    private MqttService mqttService;

    @Resource
    private ICamelliaEnvSysService camelliaEnvSysService;

    @Resource
    private ICamelliaEnvThresholdService camelliaEnvThresholdService;
    public static volatile List<CamelliaDevice> deviceList = new ArrayList<>();
    public static Map<String, Integer> deviceMap = new HashMap<>();

    public static List<CamelliaEnvSys> camelliaEnvSysList = new ArrayList<>();

    @Scheduled(initialDelay = 500, fixedRate = 1 * 60 * 60 * 1000)
    public void synDict() {
        List<CamelliaEnvSys> list = camelliaEnvSysService.list();
        camelliaEnvSysList.clear();
        camelliaEnvSysList.addAll(list);

    }


    /**
     * 更新设备的在线状态
     */
    @Scheduled(initialDelay = 5000, fixedRate = 10000)
    public void synDeviceOnlineState() {
        //获取所有在线的设备
        MqttClientInfo clientsInfo = httpApi.getClientsInfo();
        //获取数据库中的所有设备
        Page<CamelliaDevice> page = new Page<CamelliaDevice>(1, Integer.MAX_VALUE);
        IPage<CamelliaDevice> pageList = camelliaDeviceService.page(page);
        deviceList = pageList.getRecords();
        //暂时将所有设备在新状态置为离线
        deviceList.forEach((item) -> {
            item.setDeviceOnlineStatus(0);
        });
        if (clientsInfo != null && clientsInfo.getData().size() > 0) {
            List<MqttClientInfo.DataBean> clients = clientsInfo.getData();
            for (MqttClientInfo.DataBean clientBean : clients) {
                for (CamelliaDevice camelliaDevice : deviceList) {
                    if (clientBean.getClientid().equals(camelliaDevice.getDevicePid())) {
                        camelliaDevice.setDeviceOnlineStatus(1);
                    }
                }
            }
            //更新状态
            camelliaDeviceService.updateBatchById(deviceList);
            deviceMap.clear();
            deviceList.forEach((item) -> {
//                if (item.getDeviceOnlineStatus() == 1) {
//                    deviceMap.put(item.getDevicePid(), Integer.parseInt(item.getDeviceType()));
//                }
                deviceMap.put(item.getDevicePid(), Integer.parseInt(item.getDeviceType()));

            });
        }
    }

    /**
     * 更新平台所有设备的的订阅主题
     */
    @Scheduled(initialDelay = 3000, fixedRate = 5000)
    public void synAndSubscribeDeviceMqttTopic() {
        //获取数据库中的所有设备
        Page<CamelliaDevice> page = new Page<CamelliaDevice>(1, Integer.MAX_VALUE);
        IPage<CamelliaDevice> pageList = camelliaDeviceService.page(page);
        deviceList = pageList.getRecords();
        //将启用状态为1的设备的所有topic 添加到topic 监听列表
        deviceList.forEach((item) -> {
            if (item.getDeviceEnabled() == 1) {
                String mqttClientId = item.getDevicePid();
                String dataPostTopic = String.format("/%s/data/post", mqttClientId);
                String eventPostTopic = String.format("/%s/event/post", mqttClientId);
                String controlResponseTopic = String.format("/%s/control/response", mqttClientId);
                String askTopic = String.format("/%s/sys/ask", mqttClientId);
                String ntpResponse = String.format("/%s/ntp/response", mqttClientId);
                mqttService.addSubscribeTopic(dataPostTopic);
                mqttService.addSubscribeTopic(eventPostTopic);
                mqttService.addSubscribeTopic(controlResponseTopic);
                mqttService.addSubscribeTopic(askTopic);
                mqttService.addSubscribeTopic(ntpResponse);
            }
        });

    }



//    @Scheduled(initialDelay = 3000, fixedRate = 5000)
    public void mockCamelliaDeviceStatus() {
        MqttCamelliaStatusBean mqttCamelliaStatusBean = new MqttCamelliaStatusBean();
        double random = 0;
        final int CONST_V = 220;
        mqttCamelliaStatusBean.setWaterTank(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V,random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setCompressor(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setVacuumPump(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setSolventPump(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setWaterPump(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setAirCompressor(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setRefrigerator(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setCamelliaDevice(new CamelliaSubDeviceStatus(random = Math.random()*20, random*CONST_V, random < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setCamelliaSolenoidStatus(new CamelliaSolenoidStatus(Math.random() > 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,
                Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,
                Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,
                Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,
                Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1,Math.random() < 0.5 ? 0 : 1));
        mqttCamelliaStatusBean.setCamelliaStatus(Math.random() < 0.5 ? 0 : 1);
        mqttCamelliaStatusBean.setCamelliaDevicePressure(new CamelliaDevicePressure(Math.random()*1000,Math.random()*1000,Math.random()*1000,Math.random()*1000,Math.random()*1000));
        mqttCamelliaStatusBean.setCamelliaDeviceTem(new CamelliaDeviceTem(Math.random()*100,Math.random()*100,Math.random()*100,Math.random()*100,Math.random()*100));
        mqttCamelliaStatusBean.setProcessStep(new String[]{String.valueOf(new Random().nextInt(24) + 1)});
        mqttService.sendMessage("/camellia_01/data/post",JSON.toJSONString(mqttCamelliaStatusBean),0);






    }

}
